'''
Provide common dependencies
'''
from importlib import import_module
import os
import tempfile
import time

import pymysql
import pytest

from task import Task
from utils.time_drift import schema_drift

from . import EndAlert


SCHEMA_TEST_DATA = '''CREATE TABLE IF NOT EXISTS test (
    `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    `name` VARCHAR(20),
    `timestamp` BIGINT UNSIGNED)
'''


@pytest.fixture
def conn():
    '''Database connection'''
    database = pymysql.connect(**import_module('config_test').DB_CONFIG)
    schema_drift(database)
    with database.cursor() as cur:
        cur.execute(SCHEMA_TEST_DATA)

    yield database

    with database.cursor() as cur:
        cur.execute('DROP TABLE test')
        cur.execute('DROP TABLE time_drift')


class ProducerMock():
    '''Fake message producer'''

    def __init__(self):
        self.index = 0
        self.expectations = []
        self.busy = False

    def send(self, topic, data):
        '''Mock of send method, checking message'''
        if self.index >= len(self.expectations):
            raise EndAlert
        assert self.expectations[self.index] == (topic, data)
        self.index += 1

    def flush(self):
        '''Mock of flush method'''
        if self.busy:
            time.sleep(0.8)


@pytest.fixture
def producer():
    '''Fake message producer instance'''
    return ProducerMock()


@pytest.fixture
def task():
    '''Fake release task'''
    return Task(tables=['test', ], colnames=['name', 'timestamp'],
                msg_column='timestamp', time_column='timestamp',
                topic='topic', classification='alias')


@pytest.fixture
def storage():
    '''Tempory folder to store history data'''
    with tempfile.TemporaryDirectory() as tmpdirname:
        yield tmpdirname


@pytest.fixture
def lastrun():
    '''Tempory path to store timestamp'''
    with tempfile.TemporaryDirectory() as tmpdirname:
        yield os.path.join(tmpdirname, '.lastrun')
